import {loadMenus} from '@/request/services';
import {isEmpty, isNotEmpty, listToTrees} from '@/utils/CommonUtils';
import MyStorage from '@/store/MyStorage';
import router from '@/router';

function createRouter(item) {
  let route = {
    path: item.path,
    title: item.menuName,
    name: item.menuName,
    component: () => import(`@/views/${item.component}`)
  };
  if (isNotEmpty(item.menuName)) {
    route.meta = {
      title: item.menuName
    }
  }
  return route;
}

export default {
  namespaced: true,
  state: () => ({
    menus: [],
    fullScreen: false,
    layoutType: 'traditional',
  }),
  getters: {
    menus(state) {
      return state.menus;
    },
    fullScreen(state) {
      return state.fullScreen;
    },
    layoutType(state) {
      return state.layoutType;
    },
  },
  mutations: {
    setMenus(state, menus) {
      state.menus = menus;
      MyStorage.setObject('menus', menus);
    },
    setLayoutType(state, layoutType) {
      state.layoutType = layoutType;
      MyStorage.setItem('layoutType', layoutType);
    },
    setFullScreen(state, fullScreen) {
      state.fullScreen = fullScreen;
    }
  },
  actions: {
    loadMenus({commit}) {
      return new Promise((resolve, reject) => {
        loadMenus().then(data => {
          let list = data.result;
          if (isEmpty(list) || list.length <= 0) {
            resolve();
            return;
          }
          let menus = menuListToMenu(list);
          for (let i = 0; i < list.length; i++) {
            let item = list[i];
            let route = createRouter(item);
            if (isNotEmpty(route.path)) {
              router.addRoute('home', route);
            }
          }
          commit('setMenus', menus);
          resolve();
        }).then(error => {
          reject(error);
        });
      });
    },
    setFullScreen({commit}, fullScreen) {
      commit('setFullScreen', fullScreen);
    },
    setLayoutType({commit}, setLayoutType) {
      commit('setLayoutType', setLayoutType);
    },
    loadStorage({commit}) {
      let s = MyStorage;
      let data = s.getObject('menus');
      let layoutType = s.getItem('layoutType');
      if (isEmpty(layoutType)) layoutType = 'traditional';

      if (!data) data = [];
      commit('setMenus', data);
      commit('setLayoutType', layoutType);
    },
  }
};

function menuListToMenu(list) {
  for (let i = 0; i < list.length; i++) {
    list[i].name = list[i].menuName;
  }
  // console.log(listToTrees(list))
  return listToTrees(list);
}
